package com.seestech.sell.web.pay;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.lijing.wechatpay.impl.PayImpl;
import com.seestech.sell.common.utils.PayConstants;
import com.seestech.sell.common.utils.XStreamUtils;
import com.seestech.sell.domain.model.CompanyPay;
import com.seestech.sell.domain.model.Order;
import com.seestech.sell.domain.model.pay.WeichatBaseResult;
import com.seestech.sell.domain.model.pay.WeichatNotifyResult;
import com.seestech.sell.service.ICompanyPayService;
import com.seestech.sell.service.ICustomerService;
import com.seestech.sell.service.IOrderService;
import com.seestech.sell.web.SuperController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Map;



/**
 * Created by idiot on 2017/6/26.
 * @description   支付回调通知
 */
@Controller
public class PayController extends SuperController {
    private static Logger logger = LoggerFactory.getLogger(PayController.class);

    @Resource
    private IOrderService orderService;
    @Resource
    private ICustomerService customerService;
    @Resource
    private ICompanyPayService companyPayService;

    /**
     * @description   微信支付回调接口
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "weichatpay.do")
    @ResponseBody
    public String weichatNotifyResult() throws Exception {
        logger.info("微信扫码支付通知==========》》");
        String result = InputStreamToString(request_local.get().getInputStream());
        WeichatNotifyResult weichatNotifyResult = (WeichatNotifyResult) PayImpl.turnObject(WeichatNotifyResult.class, result);

        WeichatBaseResult weichatBaseResult = new WeichatBaseResult();
        if("SUCCESS".equals(weichatNotifyResult.getResult_code())){
            logger.info("回调成功==========》》");
            //根据订单号查询订单信息
            Long orderId = Long.parseLong(weichatNotifyResult.getOut_trade_no());
            Order order = orderService.getOrderByOrderId(orderId);
            if(order != null) {
                if(order.getSuccess() != 1){
                    //修改订单为完成状态  减库存
                    order.setSuccess(1);    //修改订单为完成状态
                    order.setCustomerId(weichatNotifyResult.getOpenid());   //顾客openid
                    orderService.update(order);     //修改订单
                    //更新客户积分信息表
                    customerService.modify(weichatNotifyResult.getOpenid(), order.getPrice());
                    //返回消息
                    weichatBaseResult.setReturn_code("SUCCESS");
                    weichatBaseResult.setReturn_msg("ok");
                }else {
                    weichatBaseResult.setReturn_code("SUCCESS");
                    weichatBaseResult.setReturn_msg("ok");
                }
            }else {
                weichatBaseResult.setReturn_code("FAIL");
                weichatBaseResult.setReturn_msg("无效的订单号");
            }
        }
        String res = XStreamUtils.xmlToBeanWithCDATA.toXML(weichatBaseResult).replaceAll("__", "_");
        logger.info("返回消息==========》》"+res);
        return res;
    }


    /**
     * @description  支付宝扫码支付通知地址
     * @return
     * @throws AlipayApiException
     */
    @RequestMapping(value = "alipay.do")
    @ResponseBody
    public String alipayNotifyResult() throws AlipayApiException {
        logger.info("支付宝扫码支付通知=============>>>>>>");
        //1. 解析请求参数
        Map<String, String> params = RequestUtil.getRequestParams(request_local.get());
        logger.info("请求参数===============>>>>>>>>>>>>>"+params);
        String result = "fail";
        //获取交易订单号
        Long orderId = Long.parseLong(params.get("out_trade_no"));
        // 根据订单编号 关联企业信息   加载企业支付配置信息
        CompanyPay companyPay = companyPayService.getCompanyPayByOrderId(orderId);
        if (companyPay == null){
            logger.error("支付宝扫码支付通知=============>>>>>>企业支付配置不存在");
            return result;
        }
        // 判断企业支付配置 中的微信或者支付宝是否开启  没开启返回错误提示信息
        if (companyPay != null && (companyPay.getOpenWechatPay() == 0 && companyPay.getOpenAlipay() == 0)){
            logger.error("支付宝扫码支付通知=============>>>>>>企业支付配置未开启");
            return result;
        }
        //2. 验证签名
        if(AlipaySignature.rsaCheckV1(params, companyPay.getAlipayPublicKey(),
                PayConstants.charset, companyPay.getAlipaySignType())){
            logger.info("验签成功======>>>>>>");
            //获取支付状态   TRADE_SUCCESS  为支付成功
            if(params.get("trade_status").equals("TRADE_SUCCESS")){
                Order order = orderService.getOrderByOrderId(orderId);
                //当订单存在  且  支付状态不为成功时
                if(order != null && order.getSuccess() != 1){
                    if(Double.parseDouble(params.get("total_amount")) == order.getPrice()){
                        //修改订单为完成状态  减库存
                        order.setSuccess(1);    //修改订单为完成状态
                        order.setCustomerId(params.get("buyer_id"));  //买家支付宝用户号
                        orderService.update(order);
                        //更新客户积分信息表
                        customerService.modify(params.get("buyer_id"), order.getPrice());
                        //返回消息
                        result = "success";
                    }
                }else {
                    result = "success";
                }
            }
        }else {
            logger.error("验签失败======>>>>>>");
        }
        return result;
    }


    public String InputStreamToString(InputStream is) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(is));

        StringBuffer result = new StringBuffer();
        String line;
        while ((line = br.readLine()) != null) {
            result.append(line);
        }
        br.close();
        return result.toString();
    }


}
